package com.yql.core.service.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.yql.common.ExceptionCodes;
import com.yql.common.config.WxApiConfig;
import com.yql.commonextend.utils.HttpUtils;
import com.yql.core.service.WechatLoginService;
import com.yql.biz.vo.UserLoginVo;
import com.yql.common.utils.StringUtils;
import com.yql.commonextend.response.CommonResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;




@Service
public class
WechatLoginServiceImpl implements WechatLoginService {

    private static final Logger log = LoggerFactory.getLogger(WechatLoginServiceImpl.class);

    private static final String WX_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token";

    private static final String WX_USERINFO_URL = " https://api.weixin.qq.com/sns/userinfo";


    /**
     * @description 静默授权
     * @param
     * @return
     * @author
     */
    @Override
    public CommonResponse baseAuthorization(String code) {
        if (StringUtils.isBlank(code)) {
            return CommonResponse.RespWithCodeMsg(ExceptionCodes.MSG_1071.code(), ExceptionCodes.MSG_1071.msg());
        }
        String param = "?appid="+ WxApiConfig.getAppid() + "&secret=" + WxApiConfig.getSecret() + "&code=" + code + "&grant_type=authorization_code";
        JSONObject jsonObject = HttpUtils.get(WX_ACCESS_TOKEN_URL, param);
        String openid = jsonObject.getStr("openid");
        String accessToken = jsonObject.getStr("access_token");
        UserLoginVo userLoginVo = UserLoginVo.builder().openid(openid).accessToken(accessToken).build();
        if (StringUtils.isBlank(openid)) {
            return CommonResponse.RespWithCodeMsg(ExceptionCodes.MSG_1072.code(), ExceptionCodes.MSG_1072.msg());
        }
        return CommonResponse.successWithData(userLoginVo);
    }

    /**
     * @description: 非静默授权
     * @param:
     * @return:
     * @author
     */
    @Override
    public CommonResponse userinfoAuthorization(String code) {
        UserLoginVo userLoginVo =(UserLoginVo) this.baseAuthorization(code).getData();
        String accessToken = userLoginVo.getAccessToken();
        String openid = userLoginVo.getOpenid();
        //通过 openid access_token 换取用户信息
        String param = "?access_token="+accessToken+"&openid="+openid+"&lang=zh_CN";
        JSONObject userInfoJson = HttpUtils.get(WX_USERINFO_URL, param);
        return CommonResponse.successWithData(userInfoJson);
    }

}
